import serial
import pyqtgraph as pg
from pyqtgraph.exporters import ImageExporter
from pyqtgraph.Qt import QtCore
from pyqtgraph.Qt.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QPushButton, QLabel, QComboBox, QGridLayout, QRadioButton, QFileDialog
from nox import nox
import datetime

dbg = True
dbg_all = False

app = pg.mkQApp("NOX Player")

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('NOX Monitor')
        self.multi_col_layout = QHBoxLayout()

        self.col_1_layout = QVBoxLayout()

        self.serial_widget = QWidget()
        self.serial_widget.setFixedHeight(80)
        self.serial_label1 = QLabel("Serial")
        self.serial_label1.setFixedHeight(40)
        self.serial_sel = QComboBox()
        
        for ports in nox.ports():
            self.serial_sel.addItem(ports)
        # self.serial_sel.addItem("test1")
        # self.serial_sel.addItem("test2")
        
        self.serial_layout = QGridLayout(self.serial_widget)
        self.serial_layout.addWidget(self.serial_label1, 0, 0, 1, 1)
        self.serial_layout.addWidget(self.serial_sel,    1, 0, 1, 1)

        self.select_widget = QWidget()
        self.select_widget.setFixedHeight(80)
        self.select_layout = QVBoxLayout(self.select_widget)
        self.select_label1 = QLabel("Data")
        self.select_label1.setFixedHeight(40)
        self.select_layout.addWidget(self.select_label1)
        self.select_button1 = QRadioButton("Sample")
        self.select_button2 = QRadioButton("Blank")
        self.radio_widget  = QWidget()
        self.radio_widget.setFixedHeight(40)
        self.radio_layout  = QGridLayout(self.radio_widget)
        self.radio_layout.addWidget(self.select_button1, 0, 0, 1, 1)
        self.radio_layout.addWidget(self.select_button2, 0, 1, 1, 1)
        self.select_layout.addWidget(self.radio_widget)

        self.control_widget = QWidget()
        self.control_widget.setFixedHeight(160)
        self.control_label1 = QLabel("Control")
        self.control_label1.setFixedHeight(40)
        self.control_button1 = QPushButton("Start")
        self.control_button1.clicked.connect(self.start)
        self.control_button2 = QPushButton("Stop")
        self.control_button2.clicked.connect(self.stop)
        self.control_button3 = QPushButton("Save")
        self.control_button3.clicked.connect(self.save_csv)
        self.control_layout = QGridLayout(self.control_widget)
        self.control_layout.addWidget(self.control_label1,  0, 0, 1, 1)
        self.control_layout.addWidget(self.control_button1, 1, 0, 1, 1)
        self.control_layout.addWidget(self.control_button2, 2, 0, 1, 1)
        self.control_layout.addWidget(self.control_button3, 3, 0, 1, 1)

        self.col_1_layout.addWidget(self.serial_widget)
        self.col_1_layout.addWidget(self.select_widget)
        self.col_1_layout.addWidget(self.control_widget)

        self.multi_col_layout.addLayout(self.col_1_layout)

        self.win = pg.GraphicsLayoutWidget(show=True, title="Test")
        self.win.resize(600, 450)
        #win.setWindowTitle('NOX Monitor')
        pg.setConfigOptions(antialias=True)
        self.temp_plot = self.win.addPlot(title="Temperature")
        self.temp_curve = self.temp_plot.plot(pen='y')
        self.win.nextRow()
        self.photo_plot = self.win.addPlot(title="Photoresister")
        self.photo_curve = self.photo_plot.plot(pen='y')
        self.multi_col_layout.addWidget(self.win)
        self.setLayout(self.multi_col_layout)

        #win = pg.GraphicsLayoutWidget(show=True, title="Test")
        #win.resize(750, 450)
        #win.setWindowTitle('NOX Monitor')
        #pg.setConfigOptions(antialias=True)

        # self.port = '/dev/tty.usbserial-0001'
        # self.baud = 115200

        # self.nox = nox()
        self.nox = None

        #ser = serial.Serial(port, baud, timeout=1)
        #temp_plot = win.addPlot(title="Tempature")
        #temp_curve = temp_plot.plot(pen='y')
        self.temp_data = []

        self.photo_data = []

        self.counter = 0
        self.counter_data = []

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.update)
        #timer.start(1000)

    def start(self):
        port = self.serial_sel.currentText()
        self.nox = nox(port)
        self.timer.start(1000)
        self.counter_data = []
        self.counter      = 0
        self.temp_data    = []
        self.photo_data   = []
        self.temp_curve.setData(x=self.counter_data, y=self.temp_data)
        self.photo_curve.setData(x=self.counter_data, y=self.photo_data)
    
    def stop(self):
        self.timer.stop()

    def save_png(self):
        exporter1 = ImageExporter(self.temp_plot)
        exporter1.parameters()['height'] = 720
        exporter1.parameters()['width']  = 1080
        exporter1.export('temp.png')
        exporter2 = ImageExporter(self.photo_plot)
        exporter2.parameters()['height'] = 720
        exporter2.parameters()['width']  = 1080
        exporter2.export('photo.png')
    
    def save_csv(self):
        default_name=str(datetime.date.today())+"_nox_"
        if self.select_button1.isChecked():
            default_name = default_name + "sample.csv"
        elif self.select_button2.isChecked():
            default_name = default_name + "blank.csv"
        # print(default_name)
        filename, filetype = QFileDialog.getSaveFileName(self, "Save File", default_name, "CSV Files (*.csv)")
        print(filename)
        print(filetype)
        with open(filename, "w", encoding="UTF-8") as handler:
            handler.write("Counter,Temperature,Photoresister\n")
            for i in range(len(self.counter_data)):
                line = str(self.counter_data[i]) + "," + str(self.temp_data[i]) + "," + str(self.photo_data[i]) + "\n"
                handler.write(line)
    
    def update(self):
        # global dbg, ser, counter, temp_curve, photo_curve, temp_data, photo_data

        try:
            #line = self.ser.readline().decode('utf-8')
            #temp_adc = int(line[10:16], 16)
            #photo_adc = int(line[28:34], 16)
            temp_adc = self.nox.temp()
            photo_adc = self.nox.photo()

            if dbg:
                print(temp_adc, "\t", photo_adc, sep="")
                
            self.temp_data.append(temp_adc)
            self.photo_data.append(photo_adc)
            self.counter_data.append(self.counter)
            self.counter = self.counter + 1
            self.temp_curve.setData(x=self.counter_data, y=self.temp_data)
            self.photo_curve.setData(x=self.counter_data, y=self.photo_data)
        except:
            if dbg_all:
                print("Read None")

if __name__ == '__main__':
    if dbg:
        print("TEMP\t PHOTO")
    window = Window()
    window.show()
    #timer = QtCore.QTimer()
    #timer.start(1000)
    #timer.timeout.connect(window.update)
    #ser.readline()
    pg.exec()
